package u1project.client;

import u1project.common.Request;
import u1project.common.Response;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.List;
import java.util.Scanner;

/**
 * @author oldliu
 * @since 1.0
 */
public class MainClient {
    //客户端
    public static void main(String[] args) {
        Socket s = null;
        try {
            Scanner in = new Scanner(System.in);
            s = new Socket("localhost", 9999);
            ObjectOutputStream oout = new ObjectOutputStream(s.getOutputStream());
            ObjectInputStream oin = new ObjectInputStream(s.getInputStream());
            int choice = -1;//选项
            while (true) {
                System.out.println("1:登录,2:注册，3：下载，9：退出");
                choice = in.nextInt();
                if (choice == 1) {
                    System.out.print("请您输入用户名:");
                    String n = in.next();
                    System.out.print("请您输入密码:");
                    String p = in.next();
                    //构建一个Request,发送给服务端，等着他回复
                    Request request = new Request();
                    request.setAction("login");
                    request.put("name", n);
                    request.put("pass", p);
                    oout.writeObject(request);
                    oout.reset();//重置
                    Response response = (Response) oin.readObject();
                    boolean success = response.isSuccess();
                    System.out.println(success);
                } else if (choice == 2) {
                    System.out.println("注册！");
                } else if (choice == 3) {
                    Request request = new Request("download");
                    oout.writeObject(request);
                    oout.reset();//重置
                    Response response = (Response) oin.readObject();
                    if (response.isSuccess()) {
                        //小说列表读取出来
                        List<String> novellist = (List<String>) response.get("novellist");
                        System.out.println("小说信息如下：");
                        for (String novel : novellist)
                            System.out.println(novel);
                    } else {
                        System.out.println("下载小说信息失败，原因是：" + response.getMsg());
                    }
                } else if (choice == 9) {
                    break;
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                s.close();
            } catch (Exception e) {

            }
        }

    }
}
